package com.thinkcoder.service;

import com.thinkcoder.constant.AuthConstants;
import com.thinkcoder.exception.ServiceException;
import com.thinkcoder.request.ApiRequest;
import com.thinkcoder.util.Md5Util;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Slf4j
@Getter
public class AuthToken {


    /**
     * 默认失效时间1min,10ms
     */
    private static final long DEFAULT_EXPIRED_TIME_INTERVAL=10*60*1000;

    /**
     *生成的token
     */
    private String token;

    /**
     * 创建时间
     */
    private long createTime;

    /**
     * 失效时间
     */
    private long expiredTimeInterval=DEFAULT_EXPIRED_TIME_INTERVAL;

    public AuthToken(String token,long createTime){
        this.createTime=createTime;
        this.token=token;
    }

    public AuthToken(String token,long createTime,long expiredTimeInterval){
        this.createTime=createTime;
        this.token=token;
        this.expiredTimeInterval=expiredTimeInterval;
    }

    /***
     * 通过md5加密创建token
     *
     * @param originUrl
     * @param
     * @return
     */
    public static AuthToken createToken(String originUrl,String appKey,long createTime,String nonce){

        //使用map存储,加密的时候可以不区分参数顺序
        Map<String,String> paramsMap = new HashMap<>(8);

        paramsMap.put(AuthConstants.ORIGIN_URL,originUrl);
        paramsMap.put(AuthConstants.APP_KEY,appKey);
        paramsMap.put(AuthConstants.TIME_STAMP,String.valueOf(createTime));
        paramsMap.put(AuthConstants.NONCE,nonce);

        ApiRequest apiRequest = ApiRequest.buildApiRequest(paramsMap);

        try{
            String serverToken = Md5Util.encrypt(apiRequest.toString());
            return new AuthToken(serverToken,createTime);
        }catch (Exception e){
            log.error("md5加密错误");
            throw new ServiceException(10010,"md5加密错误");
        }
    }

    /***
     * 判断token是否过期
     *
     * @return
     */
    public boolean isExpired(){
        long currentTimeMillis = System.currentTimeMillis();
        //超过窗口时间,则视为过期
        if ((currentTimeMillis-this.createTime)>expiredTimeInterval) {
            return true;
        }
        return false;
    }

    /**
     * 判断客户端和服务端token是否相等
     *
     * @param clientToken
     * @return
     */
    public boolean isMatched(String clientToken){
        return this.token.equals(clientToken);
    }

    //http://localhost:8086/test?id=4&appKey=order&timeStamp=123123&nonce=423123
    public static void main(String[] args) {
        String originUrl = "http://localhost:8086/test?id=4";
        String appKey = "order";
        long timeStamp = System.currentTimeMillis();
        System.out.println(timeStamp);
        String nonce = String.valueOf(new Random().nextInt());
        System.out.println(nonce);
        AuthToken token = createToken(originUrl, appKey, timeStamp, nonce);
        System.out.println(token.getToken());
    }

}
